"use strict"

const BaseController = require("./base")
const svgCaptcha = require("svg-captcha")
const { sign } = require("jsonwebtoken")
const uuid = require("uuid")

const fs = require("fs")
class UserController extends BaseController {
  //获取所有用户信息
  async index() {
    const { ctx, service } = this
    const { pageNum, pageSize, ...where } = ctx.query
    //console.log(where)
    const result = await service.user.list(
      isNaN(pageNum) ? 1 : parseInt(pageNum),
      isNaN(pageSize) ? 3 : parseInt(pageSize),
      where
    )
    if (result) {
      this.Success({ result, msg: "获取成功" })
    } else {
      this.Error("获取失败")
    }
  }
  //获取单条用户信息
  async single() {
    const { ctx, service } = this
    const id = ctx.params.id
    const result = await service.user.single(id)
    delete result.password
    // console.log(result)
    if (result) {
      this.Success({ result, msg: "获取成功" })
    } else {
      this.Error("获取失败")
    }
  }
  //新增用户
  async create() {
    const { ctx, service } = this
    const user = ctx.request.body
    const isExists = await service.user.isExist(user.userName)
    if (isExists.length > 0) {
      this.Success({isExists,msg: "该用户已存在"})
    } else {
      user.userId = uuid.v4()
      user.password = "litao1884873780"
      const result = await service.user.create(user)
      if (result.affectedRows === 1) {
        this.Success({result, msg:"新增成功"})
      } else {
        this.Error("新增失败")
      }
    }
  }
  //修改用户
  async update() {
    const { ctx, service } = this
    const id = ctx.params.id
    const user = ctx.request.body
    user.id = id
    const result = await service.user.update(user)
    if (result.affectedRows === 1) {
      this.Success({result, msg:"新增成功"})
    } else {
      this.Error("新增失败")
    }
  }

  //删除用户
  async destroy() {
    const { ctx, service } = this
    const id = ctx.params.id
    //console.log(id)
    const result = await service.user.destroy(id)
    if (result.affectedRows === 1) {
      this.Success({result, msg:"删除成功"})
    } else {
      this.Error("删除失败")
    }
  }

  //获取验证码
  async captcha() {
    const { ctx, service } = this
    const captchaObj = svgCaptcha.create()
    ctx.session.captcha = captchaObj.text //把文本信息存放到会话中的captcha属性中
    ctx.set("Content-Type", "image/svg+xml")
    ctx.body = captchaObj.data
  }
  //验证验证码
  async checkCaptcha() {
    const { ctx, service } = this
    const captcha = ctx.request.body.captcha
    if (captcha === ctx.session.captcha) {
      this.Success({captcha, msg:"验证成功"})
    } else {
      this.Error("验证失败，验证码错误")
    }
  }
  //注册用户
  async signup() {
    const { ctx, service, app } = this
    const user = ctx.request.body
    const result = await app.mysql.insert("egg_user", user)
    if (result.affectedRows > 0) {
      this.Success({result, msg:"注册成功"})
    } else {
      this.Error("注册失败")
    }
  }
  //用户登录
  async login() {
    const { ctx, service, app } = this
    const { userName, password } = ctx.request.body
    const result = await app.mysql.select("egg_user", {
      where: { userName, password },
      limit: 1,
    })
    if (result && result.length > 0) {
      let u = JSON.parse(JSON.stringify(result[0]))
      let menu = await app.mysql.query(
        `SELECT egg_res.* from egg_role_user 
      INNER JOIN egg_role_res 
      ON egg_role_user.roleId = egg_role_res.roleId
      INNER JOIN egg_res 
      on egg_role_res.resId = egg_res.id 
      WHERE egg_role_user.userId = ?`,
        [u.id]
      )
      menu = JSON.parse(JSON.stringify(menu))
      let Meuns = []
      const map = {}
      menu.map((item) => {
        item.children = []
        map[item.id] = item //把
        if (item.parentId === 0) {
          Meuns.push(item)
        } else {
          map[item.parentId] && map[item.parentId].children.push(item)
        }
      })
      delete u.password
      delete result[0].password
      delete result[0].uuid
      this.Success({
        userinfo: result[0],
        token: sign(u, this.config.jwtSecret),
        menus: Meuns,
      })
    } else {
      this.Error("登录失败,请检查验证码、密码是否输入正确！")
    }
  }
}

module.exports = UserController
